<template>
  <div class="resource-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">音乐资源库</h1>
        <p class="page-description">浏览和管理歌曲、艺术家和风格数据</p>
      </div>
      <div class="page-actions">
        <el-button type="primary" size="large" @click="refreshData" :loading="loading">
          <el-icon><RefreshRight /></el-icon> 刷新
        </el-button>
      </div>
    </div>
    
    <div class="row-container">
      <el-card class="content-card" shadow="hover">
        <el-tabs v-model="activeTab" @tab-click="handleTabSwitch">
          <el-tab-pane label="歌曲库" name="songs">
            <div class="resource-list">
              <!-- 添加搜索框 -->
              <div class="search-container">
                <el-input
                  v-model="songSearchQuery"
                  placeholder="搜索歌曲名称"
                  clearable
                  @input="handleSongSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
              
              <el-table
                :data="filteredSongs"
                style="width: 100%"
                v-loading="activeTab === 'songs' && loading"
                element-loading-text="加载中..."
                :header-cell-style="{backgroundColor: '#f5f7fa', color: '#303133', fontWeight: '600'}"
              >
                <el-table-column
                  prop="song_id"
                  label="ID"
                  width="160"
                  show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                  label="歌手">
                  <template #default="{ row }">
                    <span>{{ formatArtists(row.artists) }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="song_name"
                  label="歌曲名称">
                </el-table-column>
                <el-table-column
                  prop="song_duration"
                  label="时长">
                  <template #default="{ row }">
                    <span>{{ formatDuration(row.song_duration) }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="110"
                  align="right">
                  <template #default="{ row }">
                    <el-button
                      size="small"
                      type="primary"
                      @click="viewSongDetail(row)">详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <div class="pagination">
                <el-pagination
                  @size-change="handleSongSizeChange"
                  @current-change="handleSongCurrentChange"
                  :current-page="songCurrentPage"
                  :page-sizes="[10, 20, 50, 100]"
                  :page-size="songPageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="songTotal"
                ></el-pagination>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="歌手库" name="artists">
            <div class="resource-list">
              <!-- 添加搜索框 -->
              <div class="search-container">
                <el-input
                  v-model="artistSearchQuery"
                  placeholder="搜索歌手名称"
                  clearable
                  @input="handleArtistSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
              </div>
              
              <el-table
                :data="filteredArtists"
                style="width: 100%"
                v-loading="activeTab === 'artists' && loading"
                element-loading-text="加载中..."
                :header-cell-style="{backgroundColor: '#f5f7fa', color: '#303133', fontWeight: '600'}"
                :row-class-name="artistTableRowClassName"
                class="artist-table"
              >
                <el-table-column
                  prop="artist_id"
                  label="ID"
                  width="90"
                  align="center">
                </el-table-column>
                <el-table-column
                  prop="artist_name"
                  label="歌手名称">
                  <template #default="{ row }">
                    <span class="artist-name-cell">{{ row.artist_name }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="songs_count"
                  label="歌曲数量"
                  width="120"
                  align="center">
                  <template #default="{ row }">
                    <el-tag type="info" effect="plain">{{ row.songs_count }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="110"
                  align="right">
                  <template #default="{ row }">
                    <el-button
                      size="small"
                      type="primary"
                      @click="viewArtistDetail(row)">详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <div class="pagination">
                <el-pagination
                  @size-change="handleArtistSizeChange"
                  @current-change="handleArtistCurrentChange"
                  :current-page="artistCurrentPage"
                  :page-sizes="[10, 20, 50, 100]"
                  :page-size="artistPageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="artistTotal"
                ></el-pagination>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    
    <!-- 数据卡片 -->
    <div class="row-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="data-card" shadow="hover">
            <div class="card-header">
              <div class="card-title">总歌曲数</div>
            </div>
            <div class="card-value">{{ songTotal }}</div>
            <div class="card-footer">系统中的音乐资源总数</div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="data-card" shadow="hover">
            <div class="card-header">
              <div class="card-title">总歌手数</div>
            </div>
            <div class="card-value">{{ artistTotal }}</div>
            <div class="card-footer">系统中的艺术家总数</div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="data-card" shadow="hover">
            <div class="card-header">
              <div class="card-title">本周播放</div>
            </div>
            <div class="card-value">{{ recentPlays }}</div>
            <div class="card-footer">最近一周的总播放次数</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 浮动操作区 -->
    <div class="floating-actions">
      <el-button type="primary" @click="refreshData" :loading="loading" class="refresh-btn">
        <el-icon><RefreshRight /></el-icon>
      </el-button>
    </div>
    
    <!-- 底部安全区域 -->
    <div class="bottom-safe-area"></div>
  </div>
</template>

<script>
import axios from 'axios';
import { RefreshRight, Search } from '@element-plus/icons-vue';

export default {
  name: 'ResourcePage',
  components: {
    RefreshRight,
    Search
  },
  data() {
    return {
      activeTab: 'songs',
      // 歌曲数据
      songs: [],
      filteredSongs: [],
      songSearchQuery: '',
      songCurrentPage: 1,
      songPageSize: 20,
      songTotal: 0,
      selectedSongs: [],
      // 歌手数据
      artists: [],
      filteredArtists: [],
      artistSearchQuery: '',
      artistCurrentPage: 1,
      artistPageSize: 20,
      artistTotal: 0,
      selectedArtists: [],
      // 统计数据
      recentPlays: 0,
      loading: false
    };
  },
  created() {
    // 页面加载时立即获取歌曲和歌手数据
    this.fetchSongs();
    this.fetchArtists();
    
    // 模拟本周播放数据
    this.recentPlays = Math.floor(Math.random() * 1000);
  },
  methods: {
    handleTabSwitch(tab) {
      // 切换tab时重置分页、搜索框并刷新数据
      if (tab.name === 'songs') {
        this.songCurrentPage = 1;
        this.songSearchQuery = '';
        this.fetchSongs();
      } else if (tab.name === 'artists') {
        this.artistCurrentPage = 1;
        this.artistSearchQuery = '';
        this.fetchArtists();
      }
    },
    formatArtists(artists) {
      if (!artists || artists.length === 0) return '';
      return artists.map(artist => artist.artist_name).join(', ');
    },
    formatDuration(seconds) {
      if (!seconds) return '00:00';
      const min = Math.floor(seconds / 60);
      const sec = seconds % 60;
      return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
    },
    refreshData() {
      if (this.activeTab === 'songs') {
        this.fetchSongs();
      } else if (this.activeTab === 'artists') {
        this.fetchArtists();
      }
    },
    async fetchSongs() {
      this.loading = true;
      try {
        const response = await axios.get(`https://smartsound.top/api/repository/songs`, {
          params: {
            page_size: this.songPageSize,
            page: this.songCurrentPage
          }
        });
        
        if (response.data.code === 200) {
          this.songs = response.data.data.songs;
          this.filteredSongs = [...this.songs]; // 初始化过滤后的歌曲列表
          this.songTotal = response.data.data.total;
        } else {
          this.$message.error('获取歌曲列表失败: ' + response.data.message);
        }
      } catch (error) {
        this.$message.error('获取歌曲列表失败: ' + error.message);
      } finally {
        this.loading = false;
      }
    },
    async fetchArtists() {
      this.loading = true;
      try {
        const response = await axios.get(`https://smartsound.top/api/repository/artists`, {
          params: {
            page_size: this.artistPageSize,
            page: this.artistCurrentPage
          }
        });
        
        if (response.data.code === 200) {
          this.artists = response.data.data.artists;
          this.filteredArtists = [...this.artists]; // 初始化过滤后的歌手列表
          this.artistTotal = response.data.data.total;
        } else {
          this.$message.error('获取歌手列表失败: ' + response.data.message);
        }
      } catch (error) {
        this.$message.error('获取歌手列表失败: ' + error.message);
      } finally {
        this.loading = false;
      }
    },
    handleSongSizeChange(size) {
      this.songPageSize = size;
      this.fetchSongs();
    },
    handleSongCurrentChange(page) {
      this.songCurrentPage = page;
      this.fetchSongs();
    },
    handleArtistSizeChange(size) {
      this.artistPageSize = size;
      this.fetchArtists();
    },
    handleArtistCurrentChange(page) {
      this.artistCurrentPage = page;
      this.fetchArtists();
    },
    async viewSongDetail(song) {
      try {
        const response = await axios.get(`https://smartsound.top/api/repository/songs/${song.id}`);
        
        if (response.data.code === 200) {
          const songDetail = response.data.data;
          this.$alert(`
            <div>
              <h3>${songDetail.song_name}</h3>
              <p><strong>歌曲ID:</strong> ${songDetail.song_id}</p>
              <p><strong>歌手:</strong> ${this.formatArtists(songDetail.artists)}</p>
              <p><strong>歌手ID:</strong> ${songDetail.artists.map(artist => artist.artist_id).join(', ')}</p>
              <p><strong>时长:</strong> ${this.formatDuration(songDetail.song_duration)}</p>
            </div>
          `, '歌曲详情', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '关闭'
          });
        } else {
          this.$message.error('获取歌曲详情失败: ' + response.data.message);
        }
      } catch (error) {
        this.$message.error('获取歌曲详情失败: ' + error.message);
      }
    },
    async viewArtistDetail(artist) {
      try {
        const response = await axios.get(`https://smartsound.top/api/repository/artists/${artist.artist_id}`);
        
        if (response.data.code === 200) {
          const artistDetail = response.data.data;
          
          // Create HTML for song list
          let songsHtml = '';
          if (artistDetail.songs && artistDetail.songs.length > 0) {
            songsHtml = '<div class="artist-songs"><h4>歌曲列表</h4><ul>';
            artistDetail.songs.forEach(song => {
              songsHtml += `<li>
                <strong>${song.song_name}</strong> 
                (ID: ${song.song_id}) - 
                ${this.formatDuration(song.song_duration)}
              </li>`;
            });
            songsHtml += '</ul></div>';
          } else {
            songsHtml = '<p>暂无歌曲信息</p>';
          }
          
          this.$alert(`
            <div class="artist-detail">
              <h3>${artistDetail.artist_name}</h3>
              <p><strong>歌手ID:</strong> ${artistDetail.artist_id}</p>
              <p><strong>歌曲数量:</strong> ${artistDetail.songs ? artistDetail.songs.length : 0}</p>
              ${songsHtml}
            </div>
          `, '歌手详情', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '关闭',
            customClass: 'artist-detail-dialog'
          });
        } else {
          this.$message.error('获取歌手详情失败: ' + response.data.message);
        }
      } catch (error) {
        this.$message.error('获取歌手详情失败: ' + error.message);
      }
    },
    viewArtistSongs(artist) {
      this.$message.success(`查看歌手 ${artist.artist_name} 的歌曲`);
      // 这里可以实现查看歌手歌曲的逻辑
    },
    // 搜索功能方法
    handleSongSearch() {
      if (!this.songSearchQuery) {
        this.filteredSongs = [...this.songs];
        return;
      }
      
      const query = this.songSearchQuery.toLowerCase();
      this.filteredSongs = this.songs.filter(song => 
        song.song_name.toLowerCase().includes(query) || 
        (song.artists && song.artists.some(artist => 
          artist.artist_name.toLowerCase().includes(query)
        ))
      );
    },
    
    handleArtistSearch() {
      if (!this.artistSearchQuery) {
        this.filteredArtists = [...this.artists];
        return;
      }
      
      const query = this.artistSearchQuery.toLowerCase();
      this.filteredArtists = this.artists.filter(artist => 
        artist.artist_name.toLowerCase().includes(query)
      );
    },
    artistTableRowClassName() {
      return 'artist-row';
    }
  }
}
</script>

<style scoped>
.resource-container {
  padding: 16px 5px;
  position: relative;
  margin-bottom: 80px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #1890ff, #722ed1);
  color: white;
  border-radius: 12px;
  padding: 32px 40px;
  margin-bottom: 35px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.page-header::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 50%;
  background: rgba(255, 255, 255, 0.1);
  transform: skewX(-20deg);
}

.header-content {
  z-index: 1;
}

.page-title {
  font-size: 28px;
  margin: 0 0 12px 0;
  font-weight: 600;
}

.page-description {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
  line-height: 1.6;
}

.page-actions {
  z-index: 1;
  display: flex;
  gap: 10px;
}

/* 行容器样式 */
.row-container {
  margin-bottom: 30px;
  position: relative;
  z-index: 0;
}

/* 内容卡片 */
.content-card {
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  transform: translate3d(0, 0, 0);
  will-change: transform;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.content-card:hover {
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
  z-index: 1;
  border-color: rgba(24, 144, 255, 0.1);
}

/* 卡片基本样式 */
.el-card {
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.03);
  transform: translate3d(0, 0, 0);
  will-change: transform;
  transition: all 0.3s;
}

.el-card:hover {
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
  z-index: 1;
  border-color: rgba(24, 144, 255, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-right: 12px;
}

.card-actions {
  display: flex;
  align-items: center;
}

/* 数据卡片样式 */
.data-card {
  height: 100%;
  padding: 10px;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin: 15px 0;
}

.card-footer {
  font-size: 13px;
  color: #909399;
}

/* 资源列表 */
.resource-list {
  padding: 10px 0;
}

/* 分页控件 */
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 表格样式 */
.el-table {
  margin: 10px 0;
  border-radius: 8px;
  overflow: hidden;
}

/* 按钮样式 */
.el-button {
  border-radius: 4px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 浮动操作区 */
.floating-actions {
  position: fixed;
  right: 24px;
  bottom: 24px;
  display: flex;
  align-items: center;
  z-index: 100;
}

.refresh-btn {
  margin-left: 0;
}

/* 底部安全区域 */
.bottom-safe-area {
  height: 60px;
  width: 100%;
  margin-top: 20px;
}

/* 自定义弹窗样式 */
:deep(.artist-detail-dialog) {
  max-width: 600px;
}

:deep(.artist-detail h3) {
  margin-top: 0;
  color: #1890ff;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

:deep(.artist-detail h4) {
  margin-top: 15px;
  margin-bottom: 10px;
  font-size: 16px;
}

:deep(.artist-songs ul) {
  padding-left: 20px;
  margin-top: 10px;
}

:deep(.artist-songs li) {
  margin-bottom: 5px;
  line-height: 1.5;
}

/* 搜索框样式 */
.search-container {
  margin-bottom: 16px;
  max-width: 400px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 24px;
  }
  
  .page-actions {
    margin-top: 20px;
    flex-wrap: wrap;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .floating-actions {
    right: 16px;
    bottom: 16px;
  }
  
  .el-row {
    flex-direction: column;
  }
  
  .el-col {
    width: 100% !important;
    margin-bottom: 20px;
  }
}

/* 歌曲ID列不换行，超出省略 */
.el-table .el-table__cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.artist-table .el-table__row.artist-row:hover {
  background-color: #f0f5ff !important;
  transition: background 0.2s;
}
.artist-table .artist-name-cell {
  font-size: 15px;
}
.artist-table .el-tag {
  font-size: 13px;
  padding: 4px 12px;
  border-radius: 4px;
}
</style>